﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using gregn6Lib;
using grdes6Lib;
using GBT_Tool_v4._0;
using System.Runtime.InteropServices;

namespace ExportMealToExcel
{
    public partial class ExportMealToExcel : Form
    {
        private Logger logger = LogManager.GetCurrentClassLogger();
        HttpRequest hr = new HttpRequest();
        ExportExcel ee = new ExportExcel();

        JArray jaHall = new JArray();
        JArray jaTcHall = new JArray();
        JArray jaMeal = new JArray();
        JArray jaMealReport = new JArray();
        JArray jaTcReport = new JArray();
        string hallName = "", hallTcName = "", mealName = "", date = "", tcDate = "";
        int hallID = 0, hallTcID = 0;

        private GridppReport Report = new GridppReport();
        private GRDesigner ReportDesigener = new GRDesigner();

        [StructLayout(LayoutKind.Sequential)]
        public struct MARGINS
        {
            public int Left;
            public int Right;
            public int Top;
            public int Buttom;
        };

        [DllImport("dwmapi.dll", PreserveSig = false)]
        private static extern bool DwmIsCompositionEnabled();
        [DllImport("dwmapi.dll", PreserveSig = false)]
        private static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS margin);

        protected override void OnLoad(EventArgs e)
        {
            if (DwmIsCompositionEnabled())
            {
                //MARGINS m = new MARGINS();
                //m.Right = m.Left = m.Top = this.Width + this.Height;
                //DwmExtendFrameIntoClientArea(this.Handle, ref m);
            }
            base.OnLoad(e);
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            base.OnPaintBackground(e);
            if (DwmIsCompositionEnabled())
            {
                //e.Graphics.Clear(Color.Black);
            }
        }

        public ExportMealToExcel()
        {
            InitializeComponent();
        }

        private void ExportMealToExcel_Load(object sender, EventArgs e)
        {
            try
            {
                //绑定食堂信息
                Thread tHall = new Thread(GetHall);
                tHall.Start();

                Thread tTcHall = new Thread(GetTcHall);
                tTcHall.Start();

                date = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                tcDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                dtpDate.Value = DateTime.Now.AddDays(1);
                dtpTcDate.Value = DateTime.Now.AddDays(1);

            }
            catch (Exception ex)
            {
                tsslMessage.ForeColor = Color.Red;
                tsslMessage.Text = ex.Message;
            }
        }

        /// <summary>
        /// 报餐明细食堂
        /// </summary>
        private void GetHall()
        {
            string hallList = "";
            hallList = hr.GBTGet(Program.host_url + "gbt/BasicInfo/DiningHall/" + Program.districtID);
            JObject joHall = JObject.Parse(hallList);
            JObject joHallRoot = (JObject)joHall["root"];
            jaHall = (JArray)joHallRoot["diningHallArray"];
            hallName = jaHall[0]["name"].ToString();
            for (int hallIndex = 0; hallIndex < jaHall.Count; hallIndex++)
            {
                if (cobHall.InvokeRequired)
                {
                    Action<string> actionDelegate = (o) =>
                    {
                        cobHall.Items.Add(o);
                    };
                    cobHall.BeginInvoke(actionDelegate, jaHall[hallIndex]["name"].ToString());
                }
            }

            //绑定餐点信息
            Thread tMeal = new Thread(GetMeal);
            tMeal.Start();
        }

        /// <summary>
        /// 报餐统计食堂
        /// </summary>
        private void GetTcHall()
        {
            string hallList = "";
            hallList = hr.GBTGet(Program.host_url + "gbt/BasicInfo/DiningHall/" + Program.districtID);
            JObject joHall = JObject.Parse(hallList);
            JObject joHallRoot = (JObject)joHall["root"];
            jaTcHall = (JArray)joHallRoot["diningHallArray"];
            hallTcName = jaTcHall[0]["name"].ToString();
            hallTcID = (int)jaTcHall[0]["id"];
            for (int hallIndex = 0; hallIndex < jaTcHall.Count; hallIndex++)
            {
                if (cobTcHall.InvokeRequired)
                {
                    Action<string> actionDelegate = (o) =>
                    {
                        cobTcHall.Items.Add(o);
                    };
                    cobTcHall.BeginInvoke(actionDelegate, jaTcHall[hallIndex]["name"].ToString());
                }
            }

            Thread t = new Thread(GetTcMealReport);
            t.Start();
        }

        private void GetMeal()
        {
            string mealList = "";
            mealList = hr.GBTGet(Program.host_url + "gbt/BasicInfo/MealList/" + Program.districtID);
            JObject joMeal = JObject.Parse(mealList);
            JObject joMealRoot = (JObject)joMeal["root"];
            jaMeal = (JArray)joMealRoot["data"];
            mealName = jaMeal[0]["name"].ToString();
            for (int mealIndex = 0; mealIndex < jaMeal.Count; mealIndex++)
            {
                if (cobMeal.InvokeRequired)
                {
                    Action<string> actionDelegate = (o) =>
                    {
                        cobMeal.Items.Add(o);
                    };
                    cobMeal.BeginInvoke(actionDelegate, jaMeal[mealIndex]["name"].ToString());
                }
            }

            Thread t = new Thread(GetMealReport);
            t.Start();
        }

        private void GetMealReport()
        {
            try
            {
                string requestJson = "";
                JObject param = new JObject();
                param["hallName"] = hallName;
                param["mealName"] = mealName;
                param["startDate"] = date;
                param["endDate"] = date;
                param["districtID"] = Program.districtID;
                requestJson = JsonConvert.SerializeObject(param);

                string result = hr.GBTPost(Program.host_url + "gbt/Meal/MealReportSelectDateAllToWindow", requestJson);
                JObject joMealReport = JObject.Parse(result);
                JObject joMealReportRoot = (JObject)joMealReport["root"];
                jaMealReport = (JArray)joMealReportRoot["data"];

                if (lvMealList.InvokeRequired)
                {
                    Action<object> actionDelegate = (o) =>
                    {
                        cobHall.Text = hallName;
                        cobMeal.Text = mealName;
                        try
                        {
                            lvMealList.Items.Clear();
                            for (int mealReportIndex = 0; mealReportIndex < jaMealReport.Count; mealReportIndex++)
                            {
                                ListViewItem lvi = new ListViewItem();
                                lvi.Text = (mealReportIndex + 1).ToString();
                                lvi.SubItems.Add(jaMealReport[mealReportIndex]["number"].ToString());
                                lvi.SubItems.Add(jaMealReport[mealReportIndex]["name"].ToString());
                                lvi.SubItems.Add(jaMealReport[mealReportIndex]["qty"].ToString());
                                lvi.SubItems.Add("份");
                                lvi.SubItems.Add(jaMealReport[mealReportIndex]["remark"].ToString());
                                lvMealList.Items.Add(lvi);
                            }

                            tsslMessage.ForeColor = Color.Black;
                            tsslMessage.Text = "就绪";
                        }
                        catch (Exception ex)
                        {
                            tsslMessage.ForeColor = Color.Red;
                            tsslMessage.Text = ex.Message;
                        }
                    };
                    lvMealList.BeginInvoke(actionDelegate, "");
                }
            }
            catch (Exception ex)
            {
                tsslMessage.ForeColor = Color.Red;
                tsslMessage.Text = ex.Message;
            }
        }

        private void GetTcMealReport()
        {
            string requestJson = "";
            JObject param = new JObject();
            param["hallID"] = hallTcID;
            param["date"] = tcDate;
            param["districtID"] = Program.districtID;
            requestJson = JsonConvert.SerializeObject(param);

            string result = hr.GBTPost(Program.host_url + "gbt/Meal/MealStatistics", requestJson);
            JObject joMealReport = JObject.Parse(result);
            JObject joMealReportRoot = (JObject)joMealReport["root"];
            jaTcReport = (JArray)joMealReportRoot["data"];

            if (lvTcList.InvokeRequired)
            {
                Action<object> actionDelegate = (o) =>
                {
                    cobTcHall.Text = hallTcName;

                    lvTcList.Items.Clear();
                    for (int tcReportIndex = 0; tcReportIndex < jaTcReport.Count; tcReportIndex++)
                    {
                        ListViewItem lvi = new ListViewItem();
                        lvi.Text = (tcReportIndex + 1).ToString();
                        lvi.SubItems.Add(jaTcReport[tcReportIndex]["mealName"].ToString());
                        lvi.SubItems.Add(jaTcReport[tcReportIndex]["qty"].ToString());
                        lvi.SubItems.Add("份");
                        lvTcList.Items.Add(lvi);
                    }

                    tsslMessage.ForeColor = Color.Black;
                    tsslMessage.Text = "就绪";
                };
                lvMealList.BeginInvoke(actionDelegate, "");
            }
        }

        private void ReportOpen()
        {
            switch (tcTap.SelectedIndex)
            {
                case 0:
                    System.Diagnostics.Process.Start(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "aa.grf", AppDomain.CurrentDomain.BaseDirectory);
                    break;
                case 1:
                    System.Diagnostics.Process.Start(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "bb.grf", AppDomain.CurrentDomain.BaseDirectory);
                    break;
            }

            //OpenFileDialog openFileDialog = new OpenFileDialog();
            //openFileDialog.Title = "选择报表文件文件";
            //openFileDialog.Filter = "grf文件|*.grf";
            //openFileDialog.FileName = string.Empty;
            //openFileDialog.FilterIndex = 1;
            //openFileDialog.Multiselect = false;
            //openFileDialog.RestoreDirectory = true;
            //openFileDialog.DefaultExt = "grf";
            //if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    System.Diagnostics.Process.Start(openFileDialog.FileName, AppDomain.CurrentDomain.BaseDirectory);
            //}
            
        }

        private void dtpDate_ValueChanged(object sender, EventArgs e)
        {
            //date = dtpDate.Value.ToString("yyyy-MM-dd");
            //Thread t = new Thread(GetMealReport);
            //t.Start();
        }

        private void cobHall_DropDownClosed(object sender, EventArgs e)
        {
            //hallName = cobHall.Text.Trim();
            ////GetMealReport();
            //Thread t = new Thread(GetMealReport);
            //t.Start();
        }

        private void cobMeal_DropDownClosed(object sender, EventArgs e)
        {
            //mealName = cobMeal.Text.Trim();
            //Thread t = new Thread(GetMealReport);
            //t.Start();
        }

        private void tsmiReportDesign_Click(object sender, EventArgs e)
        {
            try
            {
                ReportOpen();

                tsslMessage.ForeColor = Color.Black;
                tsslMessage.Text = "就绪";
            }
            catch (Exception ex)
            {
                tsslMessage.ForeColor = Color.Red;
                tsslMessage.Text = ex.Message;
            }
        }

        private void tsmiPrintPreview_Click(object sender, EventArgs e)
        {
            switch(tcTap.SelectedIndex)
            {
                case 0:
                    try
                    {
                        Report.LoadFromFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "aa.grf");
                        Report.FetchRecord -= new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                        Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                        if (!string.IsNullOrEmpty(hallName))
                        {
                            Report.ParameterByName("hallName").AsString = hallName;
                            Report.ParameterByName("mealName").AsString = mealName;
                            Report.ParameterByName("date").AsString = date;
                        }
                        Report.PrintPreview(true);

                        tsslMessage.ForeColor = Color.Black;
                        tsslMessage.Text = "就绪";
                    }
                    catch (Exception ex)
                    {
                        tsslMessage.ForeColor = Color.Red;
                        tsslMessage.Text = ex.Message;
                    }
                    break;
                case 1:
                    try
                    {
                        Report.LoadFromFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "bb.grf");
                        Report.FetchRecord -= new _IGridppReportEvents_FetchRecordEventHandler(TcReportFetchRecord);
                        Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(TcReportFetchRecord);
                        if (!string.IsNullOrEmpty(hallTcName))
                        {
                            Report.ParameterByName("hallName").AsString = hallTcName;
                            Report.ParameterByName("date").AsString = tcDate;
                        }
                        Report.PrintPreview(true);

                        tsslMessage.ForeColor = Color.Black;
                        tsslMessage.Text = "就绪";
                    }
                    catch (Exception ex)
                    {
                        tsslMessage.ForeColor = Color.Red;
                        tsslMessage.Text = ex.Message;
                    }
                    break;
            }
            
        }

        private void ReportFetchRecord()
        {
            try
            {
                if (jaMealReport.Count > 0)
                {
                    for(int mealReportIndex = 0; mealReportIndex < jaMealReport.Count; mealReportIndex++)
                    {
                        Report.DetailGrid.Recordset.Append();
                        Report.FieldByName("number").AsString = jaMealReport[mealReportIndex]["number"].ToString();
                        Report.FieldByName("name").AsString = jaMealReport[mealReportIndex]["name"].ToString();
                        Report.FieldByName("qty").AsString = jaMealReport[mealReportIndex]["qty"].ToString();
                        Report.FieldByName("unit").AsString = "份";
                        Report.DetailGrid.Recordset.Post();
                    }
                }

                tsslMessage.ForeColor = Color.Black;
                tsslMessage.Text = "就绪";
            }
            catch (Exception ex)
            {
                tsslMessage.ForeColor = Color.Red;
                tsslMessage.Text = ex.Message;
            }
        }

        private void TcReportFetchRecord()
        {
            try
            {
                if (jaTcReport.Count > 0)
                {
                    for (int tcReportIndex = 0; tcReportIndex < jaTcReport.Count; tcReportIndex++)
                    {
                        Report.DetailGrid.Recordset.Append();
                        Report.FieldByName("mealName").AsString = jaTcReport[tcReportIndex]["mealName"].ToString();
                        Report.FieldByName("qty").AsString = jaTcReport[tcReportIndex]["qty"].ToString();
                        Report.FieldByName("unit").AsString = "份";
                        Report.DetailGrid.Recordset.Post();
                    }
                }

                tsslMessage.ForeColor = Color.Black;
                tsslMessage.Text = "就绪";
            }
            catch (Exception ex)
            {
                tsslMessage.ForeColor = Color.Red;
                tsslMessage.Text = ex.Message;
            }
        }

        private void ExportMealToExcel_Shown(object sender, EventArgs e)
        {
            Login login = new Login();
            if (login.ShowDialog() == DialogResult.OK)
            {
                this.Text = "报餐明细（每天）-- 登录用户：" + login.username;
                tsslMessage.Text = login.username + " " + login.message;
            }
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 程序文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string v_OpenFolderPath = Application.StartupPath;
            System.Diagnostics.Process.Start("explorer.exe", v_OpenFolderPath);
        }

        private void dtpTcDate_ValueChanged(object sender, EventArgs e)
        {

        }

        private void btnTcQuery_Click(object sender, EventArgs e)
        {
            tcDate = dtpTcDate.Value.ToString("yyyy-MM-dd");
            Thread t = new Thread(GetTcMealReport);
            t.Start();
        }

        private void cobTcHall_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                hallTcID = (int)jaTcHall[cobTcHall.SelectedIndex]["id"];
                hallTcName = cobTcHall.Text.Trim();
            }
            catch
            { }
        }

        private void tsmiPrint_Click(object sender, EventArgs e)
        {
            switch (tcTap.SelectedIndex)
            {
                case 0:
                    try
                    {
                        Report.LoadFromFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "aa.grf");
                        Report.FetchRecord -= new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                        Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                        if (!string.IsNullOrEmpty(hallName))
                        {
                            Report.ParameterByName("hallName").AsString = hallName;
                            Report.ParameterByName("mealName").AsString = mealName;
                            Report.ParameterByName("date").AsString = date;
                        }
                        Report.Print(true);

                        tsslMessage.ForeColor = Color.Black;
                        tsslMessage.Text = "就绪";
                    }
                    catch (Exception ex)
                    {
                        tsslMessage.ForeColor = Color.Red;
                        tsslMessage.Text = ex.Message;
                    }
                    break;
                case 1:
                    try
                    {
                        Report.LoadFromFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "bb.grf");
                        Report.FetchRecord -= new _IGridppReportEvents_FetchRecordEventHandler(TcReportFetchRecord);
                        Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(TcReportFetchRecord);
                        if (!string.IsNullOrEmpty(hallTcName))
                        {
                            Report.ParameterByName("hallName").AsString = hallTcName;
                            Report.ParameterByName("date").AsString = tcDate;
                        }
                        Report.Print(true);

                        tsslMessage.ForeColor = Color.Black;
                        tsslMessage.Text = "就绪";
                    }
                    catch (Exception ex)
                    {
                        tsslMessage.ForeColor = Color.Red;
                        tsslMessage.Text = ex.Message;
                    }
                    break;
            }
            
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            hallName = cobHall.Text.Trim();
            mealName = cobMeal.Text.Trim();
            date = dtpDate.Value.ToString("yyyy-MM-dd");
            Thread t = new Thread(GetMealReport);
            t.Start();
        }

        private void tsmiExport_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                //设置文件类型
                sfd.Filter = "EXCEL|*.xls";
                //设置默认文件类型显示顺序
                sfd.FilterIndex = 1;
                //保存对话框是否记忆上次打开的目录
                sfd.RestoreDirectory = true;
                //点了保存按钮进入
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    string localFilePath = sfd.FileName.ToString(); //获得文件路径
                    ee.ExportMealReportToExcel(jaMealReport, localFilePath, hallName, mealName, date);
                }

                tsslMessage.ForeColor = Color.Black;
                tsslMessage.Text = "就绪";
            }
            catch (Exception ex)
            {
                tsslMessage.ForeColor = Color.Red;
                tsslMessage.Text = ex.Message;
            }
        }
    }
}
